const {
  http
} = require("../../../../utils/apiutils");

const util = require("../../../../utils/util")
const app = getApp()
import {
  formatTime1
} from '../../../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: 0,
    statusBar: 0,
    jobData: {},
    id: '',
    lat: 0,
    lng: 0,
    isCanDraw: false,
    bgImg: 'https://linghuoimage.xbbzp.com/FkUVOU3IK6srYPkY_EJQ6-DVaRSD',
    code_img: '',
    obj: {
      width: '750px',
      height: '1334px',
      code_width: '200px',
      code_height: '200px',
      bottom: '185px',
      left: '275px',
      btn_background: '#8E050D',
      borderWidth: '10px',
      borderRadius: '50%',
    },
    tabActive: 1,
    jy: [{
      name: 1,
      title: '志愿者'
    }, {
      name: 2,
      title: '志愿团体'
    }, ],
    show: false,
    page: 1,
    pageSize: 500,
    dataList: [],
    loading: false,
    hasMore: true,
    selfId: 0,
    totle: 0, // 报名人数
    id: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let CustomBar = getApp().globalData.CustomBar;
    let statusBar = getApp().globalData.statusBar
    this.setData({
      CustomBar: CustomBar - statusBar,
      statusBar: statusBar,
      selfId: getApp().globalData.factoryInfo ? getApp().globalData.factoryInfo.factoryId : '',
      lat: getApp().globalData.lat,
      lng: getApp().globalData.lng,
    })
    var that = this;
    wx.getSystemInfo({
      success: (result) => {
        var spx = 280 / 750 * result.windowWidth;
        var fpx = 500 / 750 * result.windowWidth;
        that.setData({
          sh: result.windowHeight - CustomBar,
          shs: result.windowHeight - CustomBar - spx,
          fpx: fpx
        })
      },
    })
    this.setData({
      id: options.id
    })

    // this.getCode()
    if (!this.data.selfId && !getApp().globalData.exist) {
      this.getComInfo()
    }
  },
  onShow() {
    this.isGetSetting()
    this.setData({
      page: 1,
      loading: false,
      hasMore: true,
      dataList:[]
    })
    this.getRyList()
  },
  isGetSetting() {
    // 判断用户是否授权
    var that = this;
    if (this.data.lng) {
      this.getDtl()
      return
    }
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.setData({
          lat: res.latitude,
          lng: res.longitude,
        })
        getApp().globalData.lng = res.longitude;
        getApp().globalData.lat = res.latitude;
        that.getDtl()
      },
      fail: function (res) {
        wx.showModal({
          title: '获取当前定位',
          content: '请打开设置，允许小程序使用位置信息',
          cancelText: '不允许',
          confirmText: '打开设置',
          success(res1) {
            if (res1.confirm) {
              wx.openSetting({
                withSubscriptions: true,
                success(res) {
                  if (res.authSetting['scope.userLocation']) {
                    wx.nextTick(() => {
                      that.isGetSetting();
                    })
                  }
                }
              })
            }
          },
          fail(err) {
            console.log(err)
          }
        })
        that.getDtl()
      },
    })
  },
  getDtl() {
    wx.showLoading()
    http.postExpressInfo({
      id: this.data.id
    }, res => {
      if (res.code == 0) {
        if (res.data.images) {
          res.data.images = res.data.images.split(',');
        }
        if (!this.data.lat == 0) {
          let ds = util.getDistance(this.data.lat, this.data.lng, res.data.lat, res.data.lng);
          if (ds > 1) {
            res.data.ds = ds.toFixed(1) + "Km"
          } else {
            res.data.ds = (ds * 1000).toFixed(0) + "m"
          }
        } else {
          res.data.ds = "未知"
          res.data.dst = 0;
        }
        this.setData({
          jobData: res.data,
          isSelf: getApp().globalData.userInfo.id == res.data.userId ? true : false
        })
      } else {
        wx.showToast({
          title: '查询失败',
          icon: "none"
        })
      }
      wx.hideLoading()
    }, err => {
      wx.showToast({
        title: err,
        icon: "none"
      })
      wx.hideLoading()
    })
  },
  toaddr(e) {
    if (!this.data.jobData.place) {
      return
    }
    wx.openLocation({ //​使用微信内置地图查看位置。
      latitude: Number(this.data.jobData.lat), //要去的纬度-地址
      longitude: Number(this.data.jobData.lng), //要去的经度-地址
      name: this.data.jobData.place.split(' ')[0],
      address: this.data.jobData.place.split(' ')[1]
    })
  },
  lookImg(e) {
    let url = e.currentTarget.dataset.url;
    let key = e.currentTarget.dataset.key;
    let imgArr = [];
    switch (key) {
      case 'img':
        imgArr = this.data.jobData.images
        break;
      case 'code':
        imgArr = [this.data.jobData.qrCode]
        break;
    }
    wx.previewImage({
      showmenu: true,
      current: url,
      urls: imgArr
    })
  },
  wc(e) {
    var that = this;
    if (this.data.jobData.status == 3) {
      wx.showToast({
        title: '事件已截止，需要请重新发布',
        icon: "none"
      })
      return false;
    };
    wx.showModal({
      title: "提示",
      content: "确定已经核实过该需求已经完成？",
      cancelText: '取消',
      confirmText: '确定',
      // if (res1.confirm) {
      showCancel: true,
      success: function (res1) {
        if (res1.cancel) {
          return
        }
        let item = e.currentTarget.dataset.item
        http.postExpressOver({
          id: item.id
        }, res => {
          if (res.code == 0) {
            wx.showToast({
              title: '操作成功',
              icon: "none"
            })
            that.setData({
              ['jobData.status']: 3
            })
          } else {
            wx.showToast({
              title: res.msg,
              icon: "none"
            })
          }
        }, err => {})
      },
    })
  },
  createShareImage() {
    console.log(this.data)
    this.setData({
      isCanDraw: !this.data.isCanDraw
    })
  },
  getCode() {
    let params = {
      path: 'pages/index/index',
      param: 'route=searchDtl&dtlId=' + this.data.id
    }
    http.createNewCode(params, res => {
      this.setData({
        code_img: 'data:image/png;base64,' + res
      })
    }, err => {})
  },
  onShareAppMessage: function () {
    var that = this;
    if (this.data.jobData.status == 3) {
      return
    }
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var code = getApp().globalData.userInfo.inviteCode
    var shareObj = {
      title: this.data.jobData.title, // 默认是小程序的名称(可以写slogan等)
      path: '/pages/index/index?route=searchGDtl&dtlId=' + that.data.id + "&code=" + code, // 默认是当前页面，必须是以‘/'开头的完整路径
      imageUrl: '',
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {

        }
      }
    }
    console.log("------------", shareObj);
    // 返回shareObj
    return shareObj;

  },
  maskTel(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.tel,
      fail(err) {
        console.log(JSON.stringify(err))
      }
    })
  },
  onChange(e) {
    this.setData({
      tabActive: e.detail.name
    })
    this.setData({
      page: 1,
      loading: false,
      hasMore: true,
      dataList: []
    })
    this.getRyList()
  },
  showType() {
    if (this.data.jobData.complete == 2) return;
    if (this.data.jobData.apply != 0) return;
    this.setData({
      show: !this.data.show
    })
  },
  typeQr(e) {

    // if(e.detail.value.name==1){
    if (!getApp().globalData.exist) {
      wx.showModal({
        title: "提示",
        content: "您还没有认证企业",
        confirmText: "去认证",
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/me/pages/savecompany/index',
            })
          }
        }
      })
      return;
    }
    wx.showLoading()
    // 报名成功
    let params = {
      id: this.data.id,
      avatar: getApp().globalData.userInfo.avatar,
      userId: getApp().globalData.userInfo.id,
      phone: getApp().globalData.userInfo.phone,
      name: getApp().globalData.userInfo.realName || getApp().globalData.userInfo.username
    }
    http.bmCollect(params, res => {
      wx.hideLoading()
      this.setData({
        hasMore: true,
        loading: false,
        dataList: []
      })
      this.getRyList()
      this.getDtl()
      wx.showToast({
        title: res.message,
        icon: 'none'
      })
    }, err => {})
    // }
    // if(e.detail.value.name==2){
    //   wx.navigateTo({
    //     url: '../jyTeam/index?id='+this.data.id,
    //   })
    // }
    // this.showType();
  },
  getRyList() {
    // 获取 报名者列表
    if (!this.data.hasMore || this.data.loading) return;
    this.data.loading = true;
    let params = {
      id: this.data.id,
    }
    http.postExpressBm(params, res => {
      if (res.code == 0) {
        if (res.data.records.length > 0) {
          res.data.records.map(item => {
            item.images = item.images ? item.images.split(',') : []
            item.createTime = formatTime1(item.createTime)
            // let reg=/(\d{3})\d{4}(\d{4})/; //正则表达式
            // let phone= item.phone.replace(reg, "$1****$2")
            // item.phone = phone
            return item
          })
          this.setData({
            dataList: [...this.data.dataList, ...res.data.records],
            page: this.data.page * 1 + 1,
            totle: res.data.total,
            loading: false
          })
        } else {
          this.setData({
            hasMore: false,
            loading: false,
            totle: res.data.total
          })
        }

      } else {
        wx.showToast({
          title: res.message,
          icon: "none",
        })
        this.data.loading = false
      }

    }, err => {})
  },
  bigImg(e) {
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      showmenu: true,
      urls: [url],
    })
  },
  backList() {
    let routeArr = getCurrentPages();

    if (routeArr.length == 1) {
      wx.reLaunch({
        url: '/pages/home/pages/searchgoods/searchcar',
      })
    } else {
      wx.navigateBack({
        delta: 1
      })
    }

  },
  edit() {
    wx.navigateTo({
      url: '../create-goods/index?id=' + this.data.id
    })
  },
  quBack() {
    let params = {
      id: this.data.id,
    }
    http.qxCollect(params, res => {
      wx.hideLoading()
      this.setData({
        hasMore: true,
        loading: false,
        dataList: [],
        pageNo: 1
      })
      this.getRyList()
      this.getDtl()
      wx.showToast({
        title: res.message,
        icon: 'none'
      })
    }, err => {})
  },
  getComInfo: function () {
    let data = {}
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getComInfo(data,
      function (res) {
        wx.hideLoading()
        console.log("-----已完成任务列表---", res);
        if (res.success) {
          if (res.data && res.data.id) {
            getApp().globalData.factoryInfo = res.data
            that.setData({
              userId: res.data.factoryId
            })
          }
        }
      },
      function (err) {
        wx.hideLoading()
      })
  },
})